import Main from 'pages/Main'
import { Layout, Switch, message } from 'antd'
import { BrowserRouter as Router } from 'react-router-dom'
import 'styles/index.scss'
import ActionBar from 'pages/ActionBar'
import CommonSign from 'pages/CommonSign'
import { useAppDispatch, useAppSelector } from 'store/hook'
import { changeOnlineStatus } from 'store/slices/systemSlice'
import { useTranslation } from 'react-i18next'
import { useEffect } from 'react'
import testConnect from 'utils/testConnect'

export default function App() {
  const dispatch = useAppDispatch()
  const { onlineStatus } = useAppSelector(state => state.system)
  const onChange = async (checked: boolean) => {
    if (checked) {
      dispatch(changeOnlineStatus(true))
      const connected = await testConnect()
      if (connected) {
        message.success('成功连接服务器！')
      } else {
        message.error('无法连接服务器！')
        dispatch(changeOnlineStatus(false))
      }
    } else {
      dispatch(changeOnlineStatus(checked))
    }
  }
  const { lang } = useAppSelector(state => state.system)
  const { t, i18n } = useTranslation()

  // 初始化语言
  useEffect(() => {
    i18n.changeLanguage(lang)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <Router basename={process.env.PUBLIC_URL}>
      <div className='app'>
        <h1 className='title'>
          <img src='logo.png' alt='logo' className='logo' /> {t('name')}
          <Switch checked={onlineStatus} checkedChildren={t('onlineStatus.online')} unCheckedChildren={t('onlineStatus.offline')} className='ml5' onChange={onChange} />
        </h1>
        <Layout className='layout'>
          <Layout.Sider theme='light'>
            <ActionBar />
          </Layout.Sider>
          <Layout.Content>
            <Main />
          </Layout.Content>
          <Layout.Sider theme='light'>
            <CommonSign />
          </Layout.Sider>
        </Layout>
      </div>
    </Router>
  )
}
